package reggie.ruiji.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import reggie.ruiji.common.R;
import reggie.ruiji.pojo.Employee;
import reggie.ruiji.pojo.PageBean;
import reggie.ruiji.service.EmployeeService;

import javax.swing.text.Document;
import java.time.LocalDate;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController
{
    @Autowired
    private EmployeeService employeeService;

   @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee)
   {

       String password = employee.getPassword();
       password= DigestUtils.md5DigestAsHex(password.getBytes());

       Employee E = employeeService.selectByUsername(employee.getUsername());
       if(E==null)
       {
           return R.error("登录失败");
       }

       if(!E.getPassword().equals(password))
       {
           return R.error("登录失败");
       }

       if(E.getStatus()==0)
       {
           return R.error("账号已禁用");


       }
        request.getSession().setAttribute("employee", E.getId());
       return R.success(E);
   }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request)//员工退出
    {
        //清理Session中保存的当前员工的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }


    @PostMapping()
    public R<String> save (@RequestBody Employee employee,HttpServletRequest request)
    {
        employeeService.insertEmployee( request,employee);

        log.info("新增员工成功");
        return  R.success("新增员工成功");

    }

    @GetMapping("/page")
    public R<PageBean> getEmps(@RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "10") Integer pageSize,String name)
    {
        PageBean S=employeeService.pagee(page,pageSize,name);

        return R.success(S);
    }


    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpServletRequest request)
    {
        log.info(employee.toString());
        employeeService.update(employee,request);
        return R.success("员工信息修改成功");
    }

    @GetMapping("/{id}")
    public R<Employee> getByid(@PathVariable Integer id)
    {
        log.info("根据id查询员工信息->"+id);
        Employee employee=employeeService.selectById(id);
        System.out.println(employee);
        if(employee==null)
        {
            return R.error("没有查询到对应员工信息");
        }
        return R.success(employee);
    }



}
